<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { getMyDonateListAPI } from '@/services/myDonate'
import { getCollectionListAPI } from '@/services/donationDetail'

// 定义组件属性
const props = defineProps({
  // 捐赠物种类列表
  donationTypes: {
    type: Array,
    default: () => [],
  },
  // 当前类型 (donate/pickup)
  type: {
    type: String,
    default: 'donate',
  },
  // 当前状态
  status: {
    type: String,
    default: '',
  },
})

// 定义子组件事件
const emit = defineEmits(['update:loading', 'cancel-order'])

// 数据状态
const state = reactive({
  list: [],
  loading: false,
  hasMore: true,
  currentPage: 1,
  pageSize: 7,
})

// 向父组件暴露方法
defineExpose({
  loadData,
  loadMoreData,
  refreshData,
  getCurrentData: () => state.list,
})

// 监听类型或状态变化，重新加载数据
watch([() => props.type, () => props.status], () => {
  // 重置状态并加载数据
  state.list = []
  state.currentPage = 1
  state.hasMore = true
  loadData()
})

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})

// 加载数据
async function loadData() {
  if (state.loading) return

  state.loading = true
  emit('update:loading', true)

  try {
    // 如果是收藏状态，使用getCollectionListAPI获取数据
    if (props.type === 'pickup' && props.status === 'favorite') {
      const res = await getCollectionListAPI()
      if (res.code === 200) {
        state.list = res.rows || []
        state.hasMore = (res.rows?.length || 0) >= state.pageSize
      }
    } else {
      // 使用原有的获取我的捐赠/取货数据API
      const res = await getMyDonateListAPI({
        type: props.type,
        status: props.status,
        pageNum: state.currentPage,
        pageSize: state.pageSize,
      })

      if (res.code === 200) {
        state.list = res.rows || []
        state.hasMore = (res.rows?.length || 0) >= state.pageSize
      }
    }
  } catch (error) {
    console.error('加载数据失败', error)
  } finally {
    state.loading = false
    emit('update:loading', false)
  }
}

// 加载更多数据
async function loadMoreData() {
  if (!state.hasMore || state.loading) return

  // 收藏列表暂不支持分页加载更多
  if (props.type === 'pickup' && props.status === 'favorite') return

  state.loading = true
  state.currentPage++
  emit('update:loading', true)

  try {
    const res = await getMyDonateListAPI({
      type: props.type,
      status: props.status,
      pageNum: state.currentPage,
      pageSize: state.pageSize,
    })

    if (res.code === 200) {
      const newRows = res.rows || []
      state.list = [...state.list, ...newRows]
      state.hasMore = newRows.length >= state.pageSize
    }
  } catch (error) {
    console.error('加载更多数据失败', error)
  } finally {
    state.loading = false
    emit('update:loading', false)
  }
}

// 刷新数据
async function refreshData() {
  state.currentPage = 1
  state.loading = true
  emit('update:loading', true)

  try {
    // 如果是收藏状态，使用getCollectionListAPI获取数据
    if (props.type === 'pickup' && props.status === 'favorite') {
      const res = await getCollectionListAPI()
      if (res.code === 200) {
        state.list = res.rows || []
        state.hasMore = false // 收藏列表暂不支持分页
      }
    } else {
      // 使用原有的获取我的捐赠/取货数据API
      const res = await getMyDonateListAPI({
        type: props.type,
        status: props.status,
        pageNum: state.currentPage,
        pageSize: state.pageSize,
      })

      if (res.code === 200) {
        state.list = res.rows || []
        state.hasMore = (res.rows?.length || 0) >= state.pageSize
      }
    }
  } catch (error) {
    console.error('刷新数据失败', error)
  } finally {
    state.loading = false
    emit('update:loading', false)
  }
}

// 处理取消订单
const handleCancelOrder = (item) => {
  // 弹出输入框让用户输入取消原因
  uni.showModal({
    title: '取消订单',
    content: '',
    editable: true,
    placeholderText: '请输入取消原因',
    success: (res) => {
      if (res.confirm) {
        if (!res.content || !res.content.trim()) {
          uni.showToast({
            title: '请输入取消原因',
            icon: 'none',
          })
          return
        }
        // 触发取消订单事件，传递订单id和取消原因
        emit('cancel-order', item.id, res.content.trim())
        // 这里实际业务代码由父组件处理
        uni.showToast({
          title: '已取消订单',
          icon: 'success',
        })
        // 刷新数据
        setTimeout(() => {
          refreshData()
        }, 500)
      }
    },
  })
}

// 是否可以取消订单（待审核或待入库状态）
const canCancel = (status) => {
  return props.type === 'donate' && (status === 0 || status === 2)
}

// 格式化状态显示
const formatStatus = (status) => {
  if (status === undefined) return '未知状态'
  const statusMap = {
    0: '待审核',
    1: '已取消',
    2: '待入库',
    3: '已完成',
    4: '已完成',
    5: '特殊处理',
    6: '待取货',
  }
  return statusMap[status] || '未知状态'
}

// 获取状态类名
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-pending',
    1: 'status-canceled',
    2: 'status-waiting',
    3: 'status-completed',
    4: 'status-completed',
    5: 'status-special',
    6: 'status-pickup',
  }
  return classMap[status] || 'status-unknown'
}

// 获取图片URL（截取第一张图片）
const getFirstImage = (images) => {
  if (!images) return '/static/images/default-image.png'
  const imageArray = images.split(',')
  return imageArray[0] || '/static/images/default-image.png'
}

// 格式化时间
const formatDate = (dateString) => {
  if (!dateString) return ''

  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')

  return `${year}-${month}-${day}`
}

// 根据categoryId获取分类名称
const getCategoryName = (categoryId) => {
  if (!categoryId) return '未分类'
  const category = props.donationTypes.find((item) => item.id === categoryId)
  return category ? category.typeName : '未知类型'
}

// 跳转到详情页
const goToDetail = (item) => {
  uni.navigateTo({
    url: `/pagesMember/my-orders/donation-detail?id=${item.id}`,
  })
}
</script>

<template>
  <view class="donation-list">
    <!-- 无数据提示 -->
    <view v-if="state.list.length === 0 && !state.loading" class="empty-tip">
      <image src="\static\images\nt-nothing.svg" mode="aspectFit" class="empty-image"></image>
      <text>暂无相关数据</text>
    </view>

    <!-- 数据列表 -->
    <view v-else class="list-container">
      <view
        v-for="(item, index) in state.list"
        :key="item.id || index"
        class="donation-item"
        @tap="goToDetail(item)"
      >
        <!-- 物品图片 -->
        <image class="item-image" :src="getFirstImage(item.images)" mode="aspectFill"></image>

        <!-- 物品信息 -->
        <view class="item-info">
          <!-- 物品类型 - 使用实际类型名称代替ID -->
          <view class="item-category">{{ getCategoryName(item.categoryId) }}</view>

          <!-- 描述 - 使用两行显示，超出部分用省略号 -->
          <view class="item-desc">{{ item.description || '暂无描述' }}</view>

          <!-- 底部信息 -->
          <view class="item-footer">
            <!-- 时间 -->
            <text class="item-time">{{ formatDate(item.updateTime) }}</text>

            <!-- 状态 -->
            <text class="item-status" :class="getStatusClass(item.status)">
              {{ formatStatus(item.status) }}
            </text>
          </view>

          <!-- 取消按钮 - 仅在待审核和待入库状态显示 -->
          <view
            v-if="canCancel(item.status)"
            class="cancel-btn"
            @tap.stop="handleCancelOrder(item)"
          >
            取消
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="state.loading" class="loading-tip">
        <text>正在加载...</text>
      </view>

      <!-- 加载完毕提示 -->
      <view v-else-if="!state.hasMore && state.list.length > 0" class="end-tip">
        <text>— 已经到底了 —</text>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.donation-list {
  padding: 20rpx;

  // 无数据提示
  .empty-tip {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60rpx 0;

    .empty-image {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 20rpx;
    }

    text {
      color: #999;
      font-size: 28rpx;
    }
  }

  // 列表容器
  .list-container {
    // 捐赠物项
    .donation-item {
      display: flex;
      background-color: #fff;
      border-radius: 12rpx;
      margin-bottom: 20rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

      // 物品图片
      .item-image {
        width: 200rpx;
        height: 200rpx;
        flex-shrink: 0;
        background-color: #f5f5f5;
      }

      // 物品信息
      .item-info {
        flex: 1;
        padding: 20rpx;
        display: flex;
        flex-direction: column;
        position: relative;

        // 物品类型
        .item-category {
          font-size: 28rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }

        // 描述 - 修改为两行显示，超出部分用省略号
        .item-desc {
          font-size: 26rpx;
          color: #666;
          margin-bottom: 15rpx;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 100%;
          line-height: 1.4;
          min-height: 73rpx; // 确保有足够的空间
        }

        // 底部信息
        .item-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: auto;

          // 时间
          .item-time {
            font-size: 24rpx;
            color: #999;
          }

          // 状态
          .item-status {
            font-size: 24rpx;
            padding: 4rpx 16rpx;
            border-radius: 20rpx;

            // 状态颜色
            &.status-pending {
              color: #e6a23c;
              background-color: #fdf6ec;
            }

            &.status-canceled {
              color: #f56c6c;
              background-color: #fef0f0;
            }

            &.status-waiting {
              color: #409eff;
              background-color: #ecf5ff;
            }

            &.status-completed {
              color: #67c23a;
              background-color: #f0f9eb;
            }

            &.status-special {
              color: #909399;
              background-color: #f4f4f5;
            }

            &.status-pickup {
              color: #e6a23c;
              background-color: #fdf6ec;
            }

            &.status-unknown {
              color: #909399;
              background-color: #f4f4f5;
            }
          }
        }

        // 取消按钮
        .cancel-btn {
          position: absolute;
          top: 10rpx;
          right: 10rpx;
          font-size: 24rpx;
          padding: 6rpx 16rpx;
          border-radius: 30rpx;
          color: #f56c6c;
          background-color: #fef0f0;
          border: 1px solid #f56c6c;
        }
      }
    }

    // 加载提示
    .loading-tip,
    .end-tip {
      text-align: center;
      padding: 20rpx 0;

      text {
        color: #999;
        font-size: 24rpx;
      }
    }
  }
}
</style>
